//
//  CycleView.m
//  16-CycleImage
//
//  Created by dllo on 16/8/4.
//  Copyright © 2016年 LST. All rights reserved.
//

#import "CycleView.h"

@interface CycleView()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong)UICollectionView *collection;
@property (nonatomic,strong)UICollectionViewFlowLayout *layout;
@property (nonatomic, strong)UIPageControl *page;
@property (nonatomic, strong)UIImageView *cycleImage;
/** 定时器时间间隔 */
@property (nonatomic, assign)CGFloat timeInterval;
/** 定时器对象*/
@property (nonatomic, strong)NSTimer *cycleTimer;
/**当前item的下标*/
@property (nonatomic, assign)NSInteger itemIndex;
/** 当前section下标*/
@property(nonatomic, assign)NSInteger currentSection;
@property (nonatomic, strong)NSTimer *timer;
@end

@implementation CycleView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.backgroundColor = [UIColor redColor];
        [self setup];
    }
    return self;
}
- (void)setup {
    [self creatCollectionView];
    [self addTimer];
}
- (void)creatCollectionView {
    _layout = [[UICollectionViewFlowLayout alloc] init];
    _layout.itemSize = self.frame.size;
    _layout.minimumLineSpacing = 0;
    _layout.minimumInteritemSpacing = 0;
    _layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _collection = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_layout];
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.showsHorizontalScrollIndicator = NO;
    _collection.backgroundColor = [UIColor blueColor];
    // 整页滚动
    _collection.pagingEnabled = YES;
    [self addSubview:_collection];
    [_collection registerClass:[CycleImageCell class] forCellWithReuseIdentifier:@"cell"];
}
- (void)createPageControl {
    _page = [[UIPageControl alloc] initWithFrame:CGRectZero];
    _page.numberOfPages = _arr.count - 2;
    [self addSubview:_page];
    [_page addTarget:self action:@selector(pageChange:) forControlEvents:UIControlEventValueChanged];
}
- (void)pageChange:(UIPageControl *)page {
    [_collection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:page.currentPage + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // 直接判断与0相等有何问题
    if (scrollView.contentOffset.x == 0) {
        //        [_collection setContentOffset:CGPointMake(_collection.bounds.size.width * (_arr.count - 2), 0)];
        [_collection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_arr.count - 2 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else if (scrollView.contentOffset.x == _collection.bounds.size.width * (_arr.count - 1)) {
        //        [_collection setContentOffset:CGPointMake((_collection.bounds.size.width), 0)];
        [_collection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _arr.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CycleImageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor greenColor];
    cell.cycleImage.image = [UIImage imageNamed:_arr[indexPath.row]];
    return cell;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    _collection.frame = self.bounds;
    _layout.itemSize = self.bounds.size;
    _page.frame = CGRectMake(150, 150, self.bounds.size.width / 3, 50);
    [_collection setContentOffset:CGPointMake(self.bounds.size.width, 0)];
    [self createPageControl];
}
- (void)setArr:(NSArray *)arr {
    _arr = arr;
    [_collection reloadData];
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.delegate != nil) {
        [self.delegate didClickItemIndexpath:indexPath];
    }
}
- (void)addTimer {
    // 仅仅是创建, 并没有加载loop中
    _timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    // 创建 一个timer添加到loop中
    self.timer =  [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
    // NSRunLoopCommonModes 和NSDefaultRunLoopMode
    // 后者代表默认状态, scheduledTimerWithTimerInterval添加为默认状态
    // 前者为多种状态, 包含默认及滚动
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    // 取消timer
//    [_timer invalidate];
//    _timer = nil;
}
- (void)nextImage {
    NSInteger page = self.page.currentPage;
    if (self.page.currentPage == _arr.count - 3) {
        page = 0;
        
        [_collection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:page + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    } else {
        page++;
        [_collection scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:page + 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    }
    self.page.currentPage = page;
    
}
- (void)closeTimer {
    [self.timer invalidate];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self closeTimer];
}
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    [self addTimer];
}
@end


@implementation CycleImageCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _cycleImage = [[UIImageView alloc]initWithFrame:self.bounds];
        [self.contentView addSubview:_cycleImage];
    }
    return self;
}

@end


